package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oms.entity.SemiProductSalesOrderProgress;
import org.jeecg.modules.oms.mapper.SemiProductSalesOrderProgressMapper;
import org.jeecg.modules.oms.service.ISemiProductSalesOrderProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.shiro.SecurityUtils;

import java.util.Date;
import java.util.List;

/**
 * 半成品销售订单进度Service实现类
 */
@Service
@Slf4j
public class SemiProductSalesOrderProgressServiceImpl extends ServiceImpl<SemiProductSalesOrderProgressMapper, SemiProductSalesOrderProgress> implements ISemiProductSalesOrderProgressService {

    @Autowired
    private SemiProductSalesOrderProgressMapper progressMapper;

    @Override
    public List<SemiProductSalesOrderProgress> getByOrderId(String orderId) {
        if (oConvertUtils.isEmpty(orderId)) {
            return null;
        }
        try {
            return progressMapper.selectByOrderId(orderId);
        } catch (Exception e) {
            log.error("根据订单ID查询进度记录失败: orderId={}", orderId, e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<SemiProductSalesOrderProgress> queryProgressPage(Page<SemiProductSalesOrderProgress> page, SemiProductSalesOrderProgress progress) {
        try {
            return progressMapper.selectProgressPage(page, progress);
        } catch (Exception e) {
            log.error("分页查询进度记录失败", e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderProgress> getByStatus(String orderId, Integer status) {
        if (oConvertUtils.isEmpty(orderId) || status == null) {
            return null;
        }
        try {
            return progressMapper.selectByStatus(orderId, status);
        } catch (Exception e) {
            log.error("根据状态查询进度记录失败: orderId={}, status={}", orderId, status, e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderProgress> getByOperator(String operatorId) {
        if (oConvertUtils.isEmpty(operatorId)) {
            return null;
        }
        try {
            return progressMapper.selectByOperator(operatorId);
        } catch (Exception e) {
            log.error("根据操作人查询进度记录失败: operatorId={}", operatorId, e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderProgress> getByOperationType(String operationType) {
        if (oConvertUtils.isEmpty(operationType)) {
            return null;
        }
        try {
            return progressMapper.selectByOperationType(operationType);
        } catch (Exception e) {
            log.error("根据操作类型查询进度记录失败: operationType={}", operationType, e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public SemiProductSalesOrderProgress getLatestByOrderId(String orderId) {
        if (oConvertUtils.isEmpty(orderId)) {
            return null;
        }
        try {
            return progressMapper.selectLatestByOrderId(orderId);
        } catch (Exception e) {
            log.error("获取订单最新进度记录失败: orderId={}", orderId, e);
            throw new JeecgBootException("获取最新进度记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProgress(SemiProductSalesOrderProgress progress) {
        try {
            if (!validateProgress(progress)) {
                throw new JeecgBootException("进度记录数据验证失败");
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (loginUser != null) {
                progress.setCreateBy(loginUser.getUsername());
                if (progress.getTenantId() == null && oConvertUtils.isNotEmpty(loginUser.getRelTenantIds())) {
                    progress.setTenantId(Integer.parseInt(loginUser.getRelTenantIds().split(",")[0]));
                }
            }

            progress.setCreateTime(new Date());
            if (progress.getChangeTime() == null) {
                progress.setChangeTime(new Date());
            }

            boolean result = this.save(progress);
            if (!result) {
                throw new JeecgBootException("保存进度记录失败");
            }

            log.info("添加进度记录成功: orderId={}, newStatus={}", progress.getOrderId(), progress.getNewStatus());
            return true;
        } catch (Exception e) {
            log.error("添加进度记录失败", e);
            throw new JeecgBootException("添加进度记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProgress(SemiProductSalesOrderProgress progress) {
        try {
            if (!validateProgress(progress)) {
                throw new JeecgBootException("进度记录数据验证失败");
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (loginUser != null) {
                progress.setUpdateBy(loginUser.getUsername());
            }

            progress.setUpdateTime(new Date());

            boolean result = this.updateById(progress);
            if (!result) {
                throw new JeecgBootException("更新进度记录失败");
            }

            log.info("更新进度记录成功: id={}", progress.getId());
            return true;
        } catch (Exception e) {
            log.error("更新进度记录失败", e);
            throw new JeecgBootException("更新进度记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProgress(String id) {
        try {
            if (oConvertUtils.isEmpty(id)) {
                throw new JeecgBootException("进度记录ID不能为空");
            }

            boolean result = this.removeById(id);
            if (!result) {
                throw new JeecgBootException("删除进度记录失败");
            }

            log.info("删除进度记录成功: id={}", id);
            return true;
        } catch (Exception e) {
            log.error("删除进度记录失败", e);
            throw new JeecgBootException("删除进度记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recordStatusChange(String orderId, Integer oldStatus, Integer newStatus, 
                                     String operatorId, String operatorName, String operationType, 
                                     String operationContent, String changeReason, String remark) {
        try {
            if (oConvertUtils.isEmpty(orderId) || newStatus == null) {
                throw new JeecgBootException("订单ID和新状态不能为空");
            }

            SemiProductSalesOrderProgress progress = new SemiProductSalesOrderProgress();
            progress.setOrderId(orderId);
            progress.setOldStatus(oldStatus);
            progress.setNewStatus(newStatus);
            progress.setOperatorId(operatorId);
            progress.setOperationType(operationType);
            progress.setOperationContent(operationContent);
            progress.setChangeReason(changeReason);
            progress.setChangeTime(new Date());
            progress.setRemark(remark);

            return addProgress(progress);
        } catch (Exception e) {
            log.error("记录状态变更失败", e);
            throw new JeecgBootException("记录状态变更失败: " + e.getMessage());
        }
    }

    @Override
    public Integer countByOrderId(String orderId) {
        try {
            if (oConvertUtils.isEmpty(orderId)) {
                return 0;
            }
            Integer result = progressMapper.countByOrderId(orderId);
            return result != null ? result : 0;
        } catch (Exception e) {
            log.error("统计进度记录数量失败: orderId={}", orderId, e);
            throw new JeecgBootException("统计进度记录数量失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderProgress> getByTimeRange(Date startTime, Date endTime) {
        if (startTime == null || endTime == null) {
            return null;
        }
        try {
            return progressMapper.selectByTimeRange(startTime, endTime);
        } catch (Exception e) {
            log.error("根据时间范围查询进度记录失败", e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchInsertProgress(List<SemiProductSalesOrderProgress> progressList) {
        try {
            if (progressList == null || progressList.isEmpty()) {
                return true;
            }

            // 获取当前用户信息
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String createBy = loginUser != null ? loginUser.getUsername() : "system";
            Integer tenantId = null;
            if (loginUser != null && oConvertUtils.isNotEmpty(loginUser.getRelTenantIds())) {
                tenantId = Integer.parseInt(loginUser.getRelTenantIds().split(",")[0]);
            }

            // 设置进度记录信息
            Date now = new Date();
            for (SemiProductSalesOrderProgress progress : progressList) {
                if (!validateProgress(progress)) {
                    throw new JeecgBootException("进度记录数据验证失败");
                }
                
                progress.setCreateBy(createBy);
                progress.setCreateTime(now);
                progress.setTenantId(tenantId);
                if (progress.getChangeTime() == null) {
                    progress.setChangeTime(now);
                }
            }

            int result = progressMapper.batchInsert(progressList);
            if (result <= 0) {
                throw new JeecgBootException("批量插入进度记录失败");
            }

            log.info("批量插入进度记录成功: count={}", progressList.size());
            return true;
        } catch (Exception e) {
            log.error("批量插入进度记录失败", e);
            throw new JeecgBootException("批量插入进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public List<SemiProductSalesOrderProgress> getByStatusRange(String orderId, Integer oldStatus, Integer newStatus) {
        if (oConvertUtils.isEmpty(orderId)) {
            return null;
        }
        try {
            return progressMapper.selectByStatusRange(orderId, oldStatus, newStatus);
        } catch (Exception e) {
            log.error("根据状态范围查询进度记录失败: orderId={}", orderId, e);
            throw new JeecgBootException("查询进度记录失败: " + e.getMessage());
        }
    }

    @Override
    public boolean validateProgress(SemiProductSalesOrderProgress progress) {
        if (progress == null) {
            return false;
        }

        // 验证必填字段
        if (oConvertUtils.isEmpty(progress.getOrderId())) {
            log.error("订单ID不能为空");
            return false;
        }
        if (progress.getNewStatus() == null) {
            log.error("新状态不能为空");
            return false;
        }
        if (progress.getChangeTime() == null) {
            log.error("变更时间不能为空");
            return false;
        }

        // 验证状态范围
        if (progress.getNewStatus() < 0 || progress.getNewStatus() > 11) {
            log.error("新状态必须在0-11之间");
            return false;
        }
        if (progress.getOldStatus() != null && 
            (progress.getOldStatus() < 0 || progress.getOldStatus() > 11)) {
            log.error("原状态必须在0-11之间");
            return false;
        }

        return true;
    }

    @Override
    public List<SemiProductSalesOrderProgress> getStatusChangeHistory(String orderId) {
        if (oConvertUtils.isEmpty(orderId)) {
            return null;
        }
        try {
            return progressMapper.selectByOrderId(orderId);
        } catch (Exception e) {
            log.error("获取订单状态变更历史失败: orderId={}", orderId, e);
            throw new JeecgBootException("获取状态变更历史失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteByOrderId(String orderId) {
        //根据orderid获取所有订单进度
        List<SemiProductSalesOrderProgress> progressList = progressMapper.selectByOrderId(orderId);
        this.removeByIds(progressList);
    }
}
